package com.my.test.java.two.jdbc;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.Map;

import com.my.test.java.annotation.Column;
import com.my.test.java.two.datasource.MyDataSource;
import com.my.test.java.two.datasource.Users;

public class PreStatement {
	
	private StatementImpl statement = new StatementImpl();
	
	
	public Object query(Connection conn,String sql,Class clazz) throws Exception{
		Map map = statement.getByCon(conn,sql,null);
		Object o = clazz.newInstance();
		Field[] fields = clazz.getDeclaredFields();
		for(Field f:fields){
			PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
			Column column = f.getAnnotation(Column.class);
			Object objPar = map.get(column.cloumn());
			Method method = pd.getWriteMethod();
			method.invoke(o, objPar);
		}
		return o;
	}
	public int insert(Connection conn,String sql,Class clazz) throws Exception{
		Map map = statement.getByCon(conn,sql,null);
		Object o = clazz.newInstance();
		Field[] fields = clazz.getDeclaredFields();
//		statement.insertByCon(conn, "insert into users(name,age) values(?,?)", "hzbbbbbb",15);
		for(Field f:fields){
			PropertyDescriptor pd = new PropertyDescriptor(f.getName(), clazz);
			Column column = f.getAnnotation(Column.class);
			Object objPar = map.get(column.cloumn());
			Method method = pd.getWriteMethod();
			method.invoke(o, objPar);
		}
		return 1;
	}
	public static void main(String[] args) throws Exception {
		MyDataSource my = new MyDataSource("jdbc:mysql://localhost:3306/sharding_1","root","");
		Connection conn = my.getConn();
		StatementImpl statement = new StatementImpl(conn);
		statement.get("SELECT * FROM t_student_1 WHERE name = ?","test31");
//		Users u = new Users();
//		u.setName("testt");
//		u.setAge(18);
//		statement.insertByCon(conn, "insert into users(name,age) values(?,?)", "hzbbbbbb",15);
		
//		String sql = "select * from users limit 1";
//		Class clazz = Users.class;
//		Users u = (Users) new PreStatement().test(conn,sql,clazz);
//		System.out.println(u.getName());
	}
}
